<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/12/15
 * Time: 14:49
 */
/**
 *  初始化违约车辆数据，生成相应的收付款单
 **/

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
	die('error');
}

if (!defined('API_ROOT_PATH')) {
	define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
	$db = new MysqliDb ([
		'host' => MYSQLDB,
		'username' => MYSQLDB_USER,
		'password' => MYSQLDB_PWD,
		'db' => MYSQLDB_DATABASE,
		'port' => 3306,
		'prefix' => 'au_',
		'charset' => 'utf8'
	]);
	return $db;
}
$db = init_db();

$bc_id = 0;
$lastId = 0;

while (true){
	$list = $db->where('status',2)->where('back_reason',NULL, ' IS')->where('bc_id',$lastId,'>')->get('breach_car',2000);
	if(empty($list)){
		logUtil('处理完成');die();
	}

	foreach ($list as $key=>$value){
		$sid = $value['sid'];
		$db->startTransaction();
		$purchaseOrderData = getPurchaseOrderInfoBySid($sid);

		if (empty($purchaseOrderData)) {
			$db->rollback();
			logUtil('车源:'.$sid.'没有采购单数据!');die();
		}
		$purchaseOrderId = $purchaseOrderData['id']; //采购单id
		$closeResult = closePurchaseOrderId($purchaseOrderId);
		if(!$closeResult){
			$db->rollback();
			logUtil('车源:'.$sid.'关闭采购单失败!');die();
		}
		$bank_account = $value['bank_account'];
		$accountData = json_decode($bank_account,true); //打款账号信息

		$paymentAmount = $value['compensate'];//金额（退车赔偿|退车扣除）
		$firstPayment = getFirstPaymentInfoByPurchaseOrderId($purchaseOrderId); //得到首付款单信息
		$compensateType = $value['compensate_type'];
		$carId = $value['car_id'];
		$breachData = [];


		if($compensateType == 1){ //退车类型 为我方违约时
			$breachData['back_reason'] = 1; // 退车原因 1 平台失误，2 卖方违约 3 平退
			$ownerCompensate = getOwnerCompensateByCarId($carId); // 得到车主补偿信息

			//print_r($ownerCompensate);
			if($ownerCompensate){
				$status = $ownerCompensate['status'];
			}else{
				$status = 2;
			}

			if(!$firstPayment){
				$paymentStatus = 0; //设置状态为0
			}else{
				$paymentStatus = $firstPayment['status'];
			}

			if ($paymentStatus == 2 || $paymentStatus == 0) { //如果是未付或者锁定状态,就作废原来的付款单。赔付平台违约金

				$lastAmount = $paymentAmount; //赔付金额 = 这次要赔付金额
				if ($firstPayment) { //如果存在付款单，就作废
					$oldPaymentData['status'] = 3; //作废原来的未付款单
					$result = voidThePaymentInfo($firstPayment['id']);
					if ($result === false) {
						$db->rollback();
						logUtil('车源:'.$sid.'作废原来的付款单失败!');die();
						return false;
					}
				}

				if($status == 2){ //已付
					$data['status'] = 1;
				}
				$data['pay_type'] = 6;
				$data['pay_way'] = 2;
				$data['amount'] = $lastAmount;
				$data['create_time'] = date('Y-m-d H:i:s', time());
				$data['bank_name'] = $accountData['bank_name'];
				$data['account_name'] = $accountData['account_name'];
				$data['card_no'] = $accountData['card_no'];
				$data['refer'] = 1; //来源于违约车辆
				$data['create_time'] = $ownerCompensate['createtime'];
				$data['update_time'] = $ownerCompensate['compensate_time'];
				$data['emp_id'] = $ownerCompensate['emp_id'];
				//$paymentId = Payment::add($data); //6,代表赔付车主的钱
				$paymentId = generatorPayment($data);
				if(!$paymentId){
					$db->rollback();
					logUtil('车源:'.$sid.'添加付款单失败!');die();
				}
				$result = addPaymentRelation($purchaseOrderId, $paymentId, '6');//6 代表 赔付车主
				if ($result === false) {
					$db->rollback();
					logUtil('车源:'.$sid.'添加付款单和采购单关系失败!');die();
				}
				$breachData['payment_id'] = $paymentId; //付款单号
			}elseif ($paymentStatus == 1) { //如果已付状态
				$amount = $firstPayment['amount']; //原来的付款金额
				$lastAmount = $amount - $paymentAmount; //最后的金额 = 原来的付款金额 - 这次赔付金额
				if ($lastAmount > 0) { //生成收款单
					$data = [
						'payment_type' => '7',
						'payment_method' => '1',
						'amount' => $lastAmount,
						'refer' => 1, //来源于违约车辆
						'emp_id' => $ownerCompensate['emp_id'],
						'create_time' => empty($ownerCompensate['createtime']) ? date('Y-m-d H:i:s', time()) : $ownerCompensate['createtime'],
						'update_time' => empty($ownerCompensate['compensate_time']) ? date('Y-m-d H:i:s', time()) : $ownerCompensate['compensate_time'],
					];
					if($status == 2){ //已付
						$data['status'] = 1;
					}
					$collectionId = generatorCollection($data);
					if ($collectionId === false) {
						$db->rollback();
						logUtil('车源:'.$sid.'添加收款单失败!');die();
					}
					if($ownerCompensate){
						$order_id = $ownerCompensate['order_id'];
					}else{
						$order_id = getNewestOrderByCarId($value['car_id']);
					}
					$result = addCollectionRelation($order_id,$collectionId,'7');//7 应收车主
					if ($result === false) {
						$db->rollback();
						logUtil('车源:'.$sid.'添加收款单关系失败!');die();
					}

					$breachData['collection_id_car'] = $collectionId; //收款单号


				} elseif ($lastAmount < 0) { //生成付款单
					if($status == 2){ //已付
						$data['status'] = 1;
					}
					$data['pay_type'] = 6;
					$data['pay_way'] = 2;
					$data['amount'] = ($paymentAmount - $amount);
					$data['create_time'] = date('Y-m-d H:i:s', time());
					$data['bank_name'] = $accountData['bank_name'];
					$data['account_name'] = $accountData['account_name'];
					$data['card_no'] = $accountData['card_no'];
					$data['refer'] = 1; //来源于违约车辆
					$data['create_time'] = $ownerCompensate['createtime'];
					$data['update_time'] = $ownerCompensate['compensate_time'];
					$data['emp_id'] = $ownerCompensate['emp_id'];

					$paymentId = generatorPayment($data);
					if(!$paymentId){
						$db->rollback();
						logUtil('车源:'.$sid.'已付车款时，添加付款单关系失败!');die();
					}

					$result = addPaymentRelation($purchaseOrderId,$paymentId,'6');//6 代表 赔付车主
					if ($result === false) {
						$db->rollback();
						logUtil('车源:'.$sid.'已付车款时，添加采购单，付款单关系失败!');die();
					}
					$breachData['payment_id'] = $paymentId; //付款单号*/
				}
			}elseif ($paymentStatus == 3)
			{
				$db->rollback();
				logUtil('车源:'.$sid.'付款单信息有误!');die();
			}
		}

		if($compensateType == 2){ //退车类型为 车商违约时
			$breachData['back_reason'] = 2; // 退车原因 1 平台失误，2 卖方违约 3 平退
			$receivableRefundData = getReceivableRefundByCarId($carId);//得到违约车辆，扣款信息
			if(empty($receivableRefundData)){
				$status = 2;
			}else{
				$status = $receivableRefundData['status'];
			}

			if(!$firstPayment){
				$paymentStatus = 0; //设置状态为0
			}else{
				$paymentStatus = $firstPayment['status'];
			}

			if ($paymentStatus == 2 || $paymentStatus == 0) { //如果是未付或者锁定状态,就直接生成收款单
				//$lastAmount = $paymentAmount; //赔付金额 = 这次要赔付金额
				if ($firstPayment) { //如果存在付款单，就作废
					$oldPaymentData['status'] = 3; //作废原来的未付款单
					$result = voidThePaymentInfo($firstPayment['id']);
					if ($result === false) {
						$db->rollback();
						logUtil('车源:'.$sid.'作废原来的付款单失败!');die();
						return false;
					}
				}

				if ($paymentAmount > 0) { //生成违约金收款单
					$data = [
						'payment_type' => '8',
						'payment_method' => '1',
						'amount' => $paymentAmount,
						'refer' => 1, //来源于违约车辆
						'emp_id' => $receivableRefundData['emp_id'],
						'create_time' => empty($receivableRefundData['createtime']) ? date('Y-m-d H:i:s', time()) : $receivableRefundData['createtime'],
						'update_time' => empty($receivableRefundData['receivable_time']) ? date('Y-m-d H:i:s', time()) : $receivableRefundData['receivable_time'],
					];
					if($status == 2){ //已付
						$data['status'] = 1;
					}
					$result = $collectionId = generatorCollection($data);
					if (!$result) {
						$db->rollback();
						logUtil('车源:'.$sid.'添加收款单失败!');die();
						return false;
					}

					if($receivableRefundData['order_id']){
						$order_id = $receivableRefundData['order_id'];
					}else{
						$order_id = getNewestOrderByCarId($value['car_id']);
					}

					$result = addCollectionRelation($order_id,$collectionId,'8');//8 车主赔付
					//$auOrderObj = new AuOrder($order_id);
					//$result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 因收车主
					if (!$result) {
						$db->rollback();
						logUtil('车源:'.$sid.'添加收款单拍单关系失败!');die();
					}
					$breachData['collection_id'] = $collectionId; //收款单号
				}
			} elseif ($paymentStatus == 1) { //如果已付状态，就要收回首付款及赔付金额。此时生成两笔收款单一笔收回首付款，一笔收回卖方的赔付
				$amount = $firstPayment['amount']; //原来的付款金额

				if ($amount > 0) { //生成 车款（首付款） 收款单
					$data = [
						'payment_type' => '7', // 应收车主
						'payment_method' => '1',
						'amount' => $amount,
						'refer' => 1, //来源于违约车辆
						'emp_id' => $receivableRefundData['emp_id'],
						'create_time' => empty($receivableRefundData['createtime']) ?  date('Y-m-d H:i:s', time()) : $receivableRefundData['createtime'],
						'update_time' => empty($receivableRefundData['receivable_time']) ? date('Y-m-d H:i:s', time()) : $receivableRefundData['receivable_time'],
					];
					if($status == 2){ //已付
						$data['status'] = 1;
					}
					$result = $collectionId = generatorCollection($data);
					if ($result === false) {
						$db->rollback();
						logUtil('车源:'.$sid.'卖方违约，添加收款单失败!');die();
					}

					if($receivableRefundData['order_id']){
						$order_id = $receivableRefundData['order_id'];
					}else{
						$order_id = getNewestOrderByCarId($value['car_id']);
					}
					$result = addCollectionRelation($order_id,$collectionId,'7');//7 应收车主

					if (!$result) {
						$db->rollback();
						logUtil('车源:'.$sid.'卖方违约，添加收款单拍单关系失败!');die();
					}
					$breachData['collection_id_car'] = $collectionId; //车款收款单号
				}
				if ($paymentAmount > 0) { //生成 赔付 收款单
					$data = [
						'payment_type' => '8', //8 车主违约金扣除
						'payment_method' => '1',
						'amount' => $paymentAmount,
						'refer' => 1, //来源于违约车辆
						'emp_id' => $receivableRefundData['emp_id'],
						'create_time' => empty($receivableRefundData['createtime']) ? date('Y-m-d H:i:s', time()) : $receivableRefundData['createtime'],
						'update_time' => empty($receivableRefundData['receivable_time']) ? date('Y-m-d H:i:s', time()) : $receivableRefundData['receivable_time'],
					];
					if($status == 2){ //已付
						$data['status'] = 1;
					}
					$result = $collectionId = generatorCollection($data);
					if (!$result) {
						$db->rollback();
						logUtil('车源:'.$sid.'卖方违约，添加收款单失败!');die();
						return false;
					}

					if($receivableRefundData['order_id']){
						$order_id = $receivableRefundData['order_id'];
					}else{
						$order_id = getNewestOrderByCarId($value['car_id']);
					}
					$result = addCollectionRelation($order_id,$collectionId,'8');//8 车主赔付

					if ($result === false) {
						$db->rollback();
						logUtil('车源:'.$sid.'卖方违约，添加收款单,拍单关系失败!');die();
						return false;
					}
					$breachData['collection_id'] = $collectionId; //收款单号
				}
			} elseif ($paymentStatus == 3) {
				$db->rollback();
				logUtil('车源:'.$sid.'卖方违约，付款单信息有误!');die();
			}
		}
		$result = updateBreachCar($breachData,$value['bc_id']);
		if($result === false){
			$db->rollback();
			logUtil('车源:'.$sid.'更新违约车辆数据失败!');die();
		}
		$db->commit();
		$lastId = $value['bc_id'];
		logUtil('车源:'.$sid.'处理成功!');
	}
}


/**
 * 根据 CarId 得到最新的拍单号
 *
 * @param $carId
 * @return array
 */
function getNewestOrderByCarId($carId){
	global $db;
	return $db->where('car_id',$carId)->orderBy('order_id')->getOne('order')['order_id'];
}

/**
 * 根据
 *
 * @param $carId
 * @return array
 */
function getCarInfoByCarId($carId){
	global $db;
	return $db->where('car_id',$carId)->getOne('cars');
}

/**
 * 通过carId 得到车主补偿信息
 *
 * @param $carId 车辆编号
 * @return array
 */
function getOwnerCompensateByCarId($carId){
	global $db;
	$data = $db->where('car_id',$carId)->getOne('car_owner_compensate');
	return $data;
}

/**
 * 通过carId 得到违约车辆扣款信息
 *
 * @param $carId 报告编号
 * @return array
 */
function getReceivableRefundByCarId($carId){
	global $db; //re_refund_type 1、违约车辆退车  receivable_refund 应收金额类型 1、补偿金额 2、扣除金额
	$data = $db->where('car_id',$carId)->where('re_refund_type',1)->where('receivable_type',2)->getOne('receivable_refund');
	return $data;
}


/**
 * 根据采购单Id，得到采购单信息
 *
 * @param $sid 采购单id
 * @return array 采购单数据
 */
function getPurchaseOrderInfoBySid($sid){
	global $db;
	$data = $db->where('sid',$sid)->getOne('purchase_order');
	return $data;
}

/**
 * 根据采购单Id，关闭采购单
 *
 * @param $id 采购单编号
 * @return bool
 */
function closePurchaseOrderId($id){
	global $db;
	$data = [
		'status' => 2
	];
	$result = $db->where('id',$id)->update('purchase_order',$data);
	if(!$result){
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 根采购单号，得到首付款信息
 *
 * @param $purchaseOrderId
 * @return array
 */
function getFirstPaymentInfoByPurchaseOrderId($purchaseOrderId){
	global $db;
	$paymentRelation = $db->where('pay_type',[1,2],'in')->where('po_id',$purchaseOrderId)->getOne('purchase_payments');
	if($paymentRelation){
		$pamentId = $paymentRelation['payment_id'];
		$paymentData = $db->where('id',$pamentId)->getOne('payment');
		return $paymentData;
	}
	return [];
}

/**
 *  作废原来的付款单
 *
 * @param $paymentId 付款单编号
 * @return bool
 */
function voidThePaymentInfo($paymentId){
	global $db;
	$data = [
		'status' => 3,
	];
	$result = $db->where('id',$paymentId)->update('payment',$data);
	if(!$result){
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 产生固定长度的随机字符串
 * @param $len
 * @param null $chars
 * @return string
 */
function genRandomChars($len, $chars = null)
{
	if (is_null($chars)) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	}
	mt_srand(10000000 * (double)microtime());
	for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
		$str .= $chars[mt_rand(0, $lc)];
	}
	return $str;
}

/**
 * 产生一个四位的随机字符串
 * @return string
 */
function gen4Chars()
{
	$strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$numbers = "0123456789";
	$randomString = genRandomChars(3);
	if (ctype_digit($randomString)) {
		$randomString = $randomString . genRandomChars(1, $strChars);
	} elseif (ctype_alpha($randomString)) {
		$randomString = $randomString . genRandomChars(1, $numbers);
	} else {
		$randomString = $randomString . genRandomChars(1);
	}
	return $randomString;
}

/**
 * 产生一个单据编号
 * @param $type
 * @param $subType
 * @param $date
 * @return string
 */
function genBillsNo($type, $subType, $date)
{
	global $db;
	if ($subType < 10) $subType = "0" . $subType;
	if($date != '0000-00-00 00:00:00'){
		$date = date("Ymd",strtotime($date));
	}else{
		$date = date("Ymd",time());
	}
	$orderNo = $type . $subType . $date . gen4Chars();
	if($type == 'CG'){ //如果是采购单
		$data = $db->where('purchase_order_nu',$orderNo)->getOne('purchase_order');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}elseif($type == 'FK')//如果是付款单
	{
		$data = $db->where('payment_no',$orderNo)->getOne('payment');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}elseif ($type == 'SK'){
		$data = $db->where('collection_no',$orderNo)->getOne('collection');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}
	return $orderNo;
}

/**
 *  生成付款单
 *
 * @param $paymentData 付款单数据
 * @return mixed
 */
function generatorPayment($paymentData)
{
	global $db;
	$paymentData['pay_way'] = 1;// 现金
	$paymentData['create_time'] = date('Y-m-d H:i:s');//创建时间
	$payment_no = genBillsNo("FK", $paymentData['pay_type'] , $paymentData['create_time']);
	if($paymentData['emp_id']){
		$employData = $db->where('emp_id',$paymentData['emp_id'])->getOne('employee');
		$paymentData['emp_name'] = $employData['real_name'];
	}else{
		$paymentData['emp_id'] = '31';
		$paymentData['emp_name'] = '系统';
	}
	$data = [
		'payment_no' => $payment_no,
		'status' => $paymentData['status'],
		'pay_type' => $paymentData['pay_type'],
		'pay_way' => $paymentData['pay_way'],
		'amount' => $paymentData['amount'],
		'card_no' => empty($paymentData['card_no']) ?  '' : $paymentData['card_no'],
		'bank_name' => empty($paymentData['bank_name']) ?  '' : $paymentData['bank_name'],
		'account_name' => empty($paymentData['account_name']) ?  '' : $paymentData['account_name'],
		'create_time' => empty($paymentData['createtime']) ? '': date('Y-m-d H:i:s',time()),
		'emp_id' => empty($paymentData['emp_id']) ?  '' : $paymentData['emp_id'],
		'emp_name' => empty($paymentData['emp_name']) ?  '' : $paymentData['emp_name'],
		'update_time' => empty($paymentData['last_update']) ? '': date('Y-m-d H:i:s',time()),
		'refer' => $paymentData['refer'],
	];
	/*if($paymentData['car_id'] == '658'){
		print_r($data);die();
	}*/
	$result = $db->insert("payment",$data);
	if(!$result){
		var_dump($result);
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 添加采购单付款关系数据
 *
 * @param int $purchaseOrderId 采购单编号
 * @param int $paymentId 付款单编号
 * @param int $paymentType 付款类型
 * @return mixed
 */
function addPaymentRelation($purchaseOrderId, $paymentId, $paymentType)
{
	global $db;
	$data = [
		'po_id' => $purchaseOrderId,
		'payment_id' => $paymentId,
		'pay_type' => $paymentType,
		'createtime' => date('Y-m-d H:i:s', time()),
	];
	$result = $db->insert('purchase_payments',$data);
	if(!$result){
		var_dump($result);
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 生成收款单
 *
 * @param $collectionData 收款单数据
 * @return bool
 */
function generatorCollection($collectionData){
	global $db;
	$collectionData['collection_no'] = genBillsNo('SK',$collectionData['payment_type'],$collectionData['create_time']);
	$empId = $collectionData['emp_id'];
	if($empId){
		$employData = $db->where('emp_id',$empId)->getOne('employee');
		$collectionData['emp_name'] = $employData['real_name'];
	}else{
		$collectionData['emp_id'] = '31';
		$collectionData['emp_name'] = '系统';
	}
	$result = $db->insert('collection',$collectionData);
	if(!$result){
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 添加收款单拍单关系
 *
 * @param $orderId 拍单号
 * @param $collectionId 收款单号
 * @param $collectionType 收款单类型
 * @return bool
 */
function addCollectionRelation($orderId, $collectionId, $collectionType)
{
	global $db;
	$data = [
		'order_id'=>$orderId,
		'collection_id' => $collectionId,
		'payment_type' => $collectionType,
		'createtime' => date('Y-m-d H:i:s',time()),
	];
	$result = $db->insert('order_collections',$data);
	if(!$result){
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 更新违约车辆数据
 *
 * @param $breachCar
 * @param $branchId
 */
function updateBreachCar($breachCar,$branchId){
	global $db;
	$db->where('bc_id',$branchId)->update('breach_car',$breachCar);
}